package top.birdhk.TestAPI.processfunction;

import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.api.java.tuple.Tuple;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.util.Collector;
import sun.awt.SunHints;
import top.birdhk.TestAPI.beans.SensorReading;

public class ProcessTest_ApplicationCase {
    public static void main(String[] args) throws Exception {

        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();


        env.setParallelism(1);

//        DataStreamSource<String> dataStream = env.readTextFile("E:\\flink\\wordcount\\src\\main\\resources\\sensor.txt");

        DataStreamSource<String> dataStream = env.socketTextStream("localhost", 7777);


        SingleOutputStreamOperator<SensorReading> inputStream = dataStream.map(line -> {
            String[] split = line.split(",");
            return new SensorReading(split[0], new Long(split[1]), new Double(split[2]));
        });


        // 测试keyedprocessFunction，先分组然后自定义处理
        inputStream.keyBy("id")
                .process(new TempConsIncreWarning(10))
                .print();


        env.execute();

    }


    // 实现自定义处理函数，检测一段时间内的温度连续上升，输出报警
    public static class TempConsIncreWarning extends KeyedProcessFunction<Tuple,SensorReading,String>{


        // 定义属性，当前统计的时间间隔
        private Integer inteval;

        public TempConsIncreWarning(Integer inteval) {
            this.inteval = inteval;
        }

        // 定义状态，保存上一次的温度值，定时器时间戳
        private ValueState<Double> lastTempState;
        private ValueState<Long> timerTsState;

        @Override
        public void open(Configuration parameters) throws Exception {
            lastTempState = getRuntimeContext().getState(new ValueStateDescriptor<Double>("last-temp", Double.class,Double.MIN_VALUE));
            timerTsState = getRuntimeContext().getState(new ValueStateDescriptor<Long>("timer-ts",Long.class));
        }

        @Override
        public void close() throws Exception {
            lastTempState.clear();
        }

        @Override
        public void processElement(SensorReading sensorReading, Context context, Collector<String> collector) throws Exception {
            // 取出状态
            Double lastTemp = lastTempState.value();
            Long timerTs = timerTsState.value();

            // 如果温度上升并且没有定时器，注册10s后的定时器，开始等待
            if (sensorReading.getTemperature() > lastTemp && timerTs == null){
                // 计算出定时器时间戳
                Long ts = context.timerService().currentProcessingTime() + inteval * 1000L;
                context.timerService().registerProcessingTimeTimer(ts);
                timerTsState.update(ts);
            }else if (sensorReading.getTemperature() < lastTemp && timerTs != null){
                // 如果温度下降，那么删除定时器
                context.timerService().deleteEventTimeTimer(timerTs);
                timerTsState.clear();
            }

            lastTempState.update(sensorReading.getTemperature());

        }


        @Override
        public void onTimer(long timestamp, OnTimerContext ctx, Collector<String> out) throws Exception {
            // 定时器触发，输出报警信息
            out.collect("传感器"+ctx.getCurrentKey().getField(0)+"温度值连续" + inteval+"s上升");
            timerTsState.clear();
        }


    }


}
